import qs from 'qs'
import router from '@/router'
// import store from '@/store'
import { login } from '@/api'
import wechatAuth from '@/utils/wechatAuth'
import { useStore } from '@/store/index';
import { storeToRefs } from "pinia";
// let whiteList = []
const { MODE } = import.meta.env

router.beforeEach(async (to, from, next) => {
  const store = useStore();
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.meta.isShowLoadding) {
    store.$patch(state => {
      state.isShowLoadding = true
    })
  }
  next()
  return false
  const { loginStatus } = storeToRefs(store)
  if (MODE === 'dev') {
    // processLogin('021lJr100lPjqP1Fyf300QcCax3lJr1f')
    next()
  } else {
    // if (whiteList.includes(to.name)) {
    //   next()
    // } else {
      console.log(loginStatus.value, 'loginStatus.value')
      switch (loginStatus.value) {
        case 0:
          wechatAuth.redirect_uri = processUrl()
          console.log( wechatAuth.authUrl, ' wechatAuth.authUrl wechatAuth.authUrl wechatAuth.authUrl')
          await store.setLoginStatus(1)
          window.location.href = wechatAuth.authUrl
          break
        case 1:
          try {
            wechatAuth.returnFromWechat(to.fullPath)
            await processLogin(wechatAuth.code)
            next()
          } catch (err) {
            await store.setLoginStatus(0)
            next()
          }
          break
        case 2:
          next()
          break
        default:
          break
      }
    // }
  }
})

/**
 * 处理url链接
 * @returns {string}
 */
function processUrl() {
  const url = window.location.href
  // 解决多次登录url添加重复的code与state问题
  const urlParams = qs.parse(url.split('?')[1])
  let redirectUrl = url
  if (urlParams.code && urlParams.state) {
    delete urlParams.code
    delete urlParams.state
    const query = qs.stringify(urlParams)
    if (query.length) {
      redirectUrl = `${url.split('?')[0]}?${query}`
    } else {
      redirectUrl = `${url.split('?')[0]}`
    }
  }
  return redirectUrl
}

/**
 * 处理登录
 * @param code
 * @returns {Promise<any>}
 */
function processLogin(code) {
  const data = {
    platformInfo: 'wxlight_h5',
    access_token: code,
    login_type: 9
  }
  const store = useStore();
  console.log(code, '等录需要的code')
  return new Promise(async (resolve, reject) => {
    try {
      const { data: { access_token, birth_day, nick_name, avatar } } = await login(data)
      await store.setLoginStatus(2)
      await store.setAccessToken(access_token)
      // await store.dispatch('setRefreshToken', refresh_token)
      await store.setUserInfo({ birth_day, nick_name, avatar })
      resolve({ status: 1, data: '登录成功' })
    } catch (err) {
      reject(err)
    }
  })
}
